package com.boe.csb.core.common.csbsdk;

import com.alibaba.csb.sdk.ContentBody;
import com.alibaba.csb.sdk.HttpCallerException;
import com.alibaba.csb.sdk.HttpParameters;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;

import java.io.*;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by tianxiang.luo on 17/1/13.
 */
public class HttpCaller {

    private static PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager();
    private static RequestConfig requestConfig;
    public static final Boolean DEBUG = Boolean.valueOf(Boolean.getBoolean("http.caller.DEBUG"));
    private static final int MAX_CONNECTION_TIMEOUT = 2000;
    private static final int MAX_SOCKET_TIMEOUT = 30000;
    private static final int MAX_CR_TIMEOUT = 2000;
    private static final int MAX_CONN = 20;
    private static final String maxConn = System.getProperty("http.caller.connection.max");
    private static final String CONN_TIMEOUT = System.getProperty("http.caller.connection.timeout");
    private static final String SO_TIMEOUT = System.getProperty("http.caller.connection.so.timeout");
    private static final String CR_TIMEOUT = System.getProperty("http.caller.connection.cr.timeout");
    public static final String trustCA = System.getProperty("http.caller.ssl.trustca");
    private static final String DEFAULT_CHARSET = "UTF-8";
    private static String defaultAK = null;
    private static String defaultSK = null;
    private static ThreadLocal<Boolean> toCurlCmd = new ThreadLocal();
    private static final long MAX_FILE_SIZE = 10485760L;

    private HttpCaller() {
    }

    public static void setCurlResponse(boolean flag) {
        toCurlCmd.set(Boolean.valueOf(true));
    }

    private static boolean isCurlResponse() {
        return toCurlCmd.get() != null && ((Boolean)toCurlCmd.get()).booleanValue();
    }

    public static void setCredential(String accessKey, String secretKey) {
        defaultAK = accessKey;
        defaultSK = secretKey;
    }

    public static String changeCharset(String result, String OldcharsetName, String charsetName) throws HttpCallerException {
        if(result == null) {
            return result;
        } else {
            try {
                return new String(result.getBytes(OldcharsetName), charsetName);
            } catch (UnsupportedEncodingException var4) {
                throw new HttpCallerException(var4);
            }
        }
    }

    public static String changeCharset(String result) throws HttpCallerException {
        return changeCharset(result, "ISO-8859-1", "UTF-8");
    }

    public static String doGet(String requestURL, String apiName, Map<String, String> paramsMap) throws HttpCallerException {
        return doGet(requestURL, apiName, paramsMap, defaultAK, defaultSK);
    }

    public static String doGet(String requestURL, String apiName, Map<String, String> paramsMap, String accessKey, String secretKey) throws HttpCallerException {
        return doGet(requestURL, apiName, (String)null, paramsMap, accessKey, secretKey);
    }

    public static String doGet(String requestURL, String apiName, String version, Map<String, String> paramsMap, String accessKey, String secretKey) throws HttpCallerException {
        HttpClientHelper.validateParams(apiName, accessKey, secretKey);
        Map urlParamsMap = HttpClientHelper.parseUrlParamsMap(requestURL);
        if(paramsMap != null) {
            urlParamsMap.putAll(paramsMap);
        }

        Map headerParamsMap = HttpClientHelper.newParamsMap(urlParamsMap, apiName, version, accessKey, secretKey);
        requestURL = HttpClientHelper.trimUrl(requestURL);
        StringBuffer params = new StringBuffer();
        Iterator newRequestURL = urlParamsMap.entrySet().iterator();

        while(newRequestURL.hasNext()) {
            Map.Entry httpGet = (Map.Entry)newRequestURL.next();
            if(params.length() > 0) {
                params.append("&");
            }

            if(httpGet.getValue() != null) {
                params.append((String)httpGet.getKey()).append("=").append(URLEncoder.encode((String)httpGet.getValue()));
            }
        }

        String newRequestURL1 = requestURL;
        if(params.length() > 0) {
            newRequestURL1 = requestURL + "?" + params.toString();
        }

        if(DEBUG.booleanValue()) {
            System.out.println("-- requestURL=" + newRequestURL1);
        }

        if(isCurlResponse()) {
            StringBuffer httpGet2 = new StringBuffer("curl ");
            httpGet2.append(HttpClientHelper.genCurlHeaders(headerParamsMap));
            httpGet2.append("\"").append(newRequestURL1).append("\"");
            return httpGet2.toString();
        } else {
            HttpGet httpGet1 = new HttpGet(newRequestURL1);
            httpGet1.addHeader("Authorization", "APPCODE fbfcefd62348423ab64bea6ff3536033");
            CloseableHttpResponse response = null;
            CloseableHttpClient httpClient = createHttpClient(newRequestURL1);

            try {
                String e;
                try {
                    HttpClientHelper.setHeaders(httpGet1, headerParamsMap);
                    if(accessKey != null && DEBUG.booleanValue()) {
                        System.out.println("-- signature parameters are " + urlParamsMap);
                    }

                    response = httpClient.execute(httpGet1);
                    e = EntityUtils.toString(response.getEntity());
                } finally {
                    if(response != null) {
                        response.close();
                    }

                    httpClient.close();
                }

                return e;
            } catch (Exception var18) {
                throw new HttpCallerException(var18);
            }
        }
    }

    private static boolean isSSLProtocol(String requestUrl) {
        return requestUrl == null?false:requestUrl.trim().toLowerCase().startsWith("https://");
    }

    private static CloseableHttpClient createHttpClient(String requestURL) {
        CloseableHttpClient httpClient = null;
        if(isSSLProtocol(requestURL)) {
            try {
                httpClient = HttpClients.custom().setHostnameVerifier(new AllowAllHostnameVerifier()).setSslcontext((new SSLContextBuilder()).loadTrustMaterial((KeyStore)null, new TrustStrategy() {
                    public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                        return true;
                    }
                }).build()).build();
            } catch (KeyManagementException var3) {
                var3.printStackTrace();
            } catch (NoSuchAlgorithmException var4) {
                var4.printStackTrace();
            } catch (KeyStoreException var5) {
                var5.printStackTrace();
            }
        } else {
            httpClient = HttpClients.createDefault();
        }

        return httpClient;
    }

    public static String doGet(String requestURL) throws HttpCallerException {
        HttpGet httpGet = new HttpGet(requestURL);
        httpGet.setConfig(requestConfig);
        if(DEBUG.booleanValue()) {
            System.out.println("requestURL=" + requestURL);
        }

        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = createHttpClient(requestURL);

        try {
            String e;
            try {
                response = httpClient.execute(httpGet);
                e = EntityUtils.toString(response.getEntity());
            } finally {
                if(response != null) {
                    response.close();
                }

                httpClient.close();
            }

            return e;
        } catch (Exception var9) {
            throw new HttpCallerException(var9);
        }
    }

    public static String doPost(String requestURL, String apiName, Map<String, String> paramsMap) throws HttpCallerException {
        return doPost(requestURL, apiName, (String)null, paramsMap);
    }

    public static String doPost(String requestURL, String apiName, String version, Map<String, String> paramsMap) throws HttpCallerException {
        return doPost(requestURL, apiName, version, paramsMap, defaultAK, defaultSK);
    }

    public static String doPost(String requestURL, String apiName, Map<String, String> paramsMap, String accessKey, String secretKey) throws HttpCallerException {
        return doPost(requestURL, apiName, (String)null, (Map)paramsMap, accessKey, secretKey);
    }

    public static String doPost(String requestURL, String apiName, String version, ContentBody cb, String accessKey, String secretKey) throws HttpCallerException {
        return doPost(requestURL, apiName, version, (Map)null, cb, accessKey, secretKey);
    }

    private static String doPost(String requestURL, String apiName, String version, Map<String, String> paramsMap, ContentBody cb, String accessKey, String secretKey) throws HttpCallerException {
        HttpClientHelper.validateParams(apiName, accessKey, secretKey);
        Object urlParamsMap = new HashMap();
        if(cb == null) {
            urlParamsMap = HttpClientHelper.parseUrlParamsMap(requestURL);
            requestURL = HttpClientHelper.trimUrl(requestURL);
        }

        if(paramsMap != null) {
            ((Map)urlParamsMap).putAll(paramsMap);
        }

        Map headerParamsMap = HttpClientHelper.newParamsMap((Map)urlParamsMap, apiName, version, accessKey, secretKey);
        if(isCurlResponse()) {
            return HttpClientHelper.createPostCurlString(requestURL, (Map)urlParamsMap, headerParamsMap, cb);
        } else {
            HttpPost httpPost = HttpClientHelper.createPost(requestURL, (Map)urlParamsMap, headerParamsMap, cb);
            httpPost.addHeader("Authorization", "APPCODE fbfcefd62348423ab64bea6ff3536033");
            httpPost.setConfig(requestConfig);
            if(accessKey != null && DEBUG.booleanValue()) {
                System.out.println("signature parameters are " + urlParamsMap);
            }

            CloseableHttpResponse response = null;
            CloseableHttpClient httpClient = createHttpClient(requestURL);

            try {
                String e;
                try {
                    response = httpClient.execute(httpPost);
                    e = EntityUtils.toString(response.getEntity());
                } finally {
                    if(response != null) {
                        response.close();
                    }

                    httpClient.close();
                }

                return e;
            } catch (Exception var17) {
                throw new HttpCallerException(var17);
            }
        }
    }

    public static String doPost(String requestURL, String apiName, String version, Map<String, String> paramsMap, String accessKey, String secretKey) throws HttpCallerException {
        return doPost(requestURL, apiName, version, paramsMap, (ContentBody)null, accessKey, secretKey);
    }

    public static String invoke(HttpParameters hp) throws HttpCallerException {
        if(hp == null) {
            throw new IllegalArgumentException("null parameter!");
        } else {
            if(DEBUG.booleanValue()) {
                System.out.println("-- httpParameters=" + hp.toString());
            }

            hp.validate();
            return "POST".equalsIgnoreCase(hp.getMethod())?doPost(hp.getRequestUrl(), hp.getApi(), hp.getVersion(), hp.getParamsMap(), hp.getContentBody(), hp.getAccessKey(), hp.getSecretkey()):doGet(hp.getRequestUrl(), hp.getApi(), hp.getVersion(), hp.getParamsMap(), hp.getAccessKey(), hp.getSecretkey());
        }
    }

    public static byte[] readFileAsByteArray(String file) throws HttpCallerException {
        File f = new File(file);
        if(f.exists() && f.isFile() && f.canRead()) {
            if(f.length() > 10485760L) {
                throw new HttpCallerException("file is too large exceed the MAX-SIZE: 10M");
            } else {
                FileInputStream ios = null;
                ByteArrayOutputStream bos = null;
                Object buffer = null;

                try {
                    ios = new FileInputStream(file);
                    bos = new ByteArrayOutputStream();
                    byte[] e = new byte[1024];

                    int n;
                    while((n = ios.read(e)) != -1) {
                        bos.write(e, 0, n);
                    }

                    byte[] buffer1 = bos.toByteArray();
                    return buffer1;
                } catch (IOException var14) {
                    throw new HttpCallerException(var14);
                } finally {
                    try {
                        if(ios != null) {
                            ios.close();
                        }

                        if(bos != null) {
                            bos.close();
                        }
                    } catch (IOException var13) {
                        ;
                    }

                }
            }
        } else {
            throw new HttpCallerException("bad file to read:" + file);
        }
    }

    public static void recoveryFileFromBytes(byte[] body, String filePath, String fileName) throws HttpCallerException {
        try {
            String e;
            if(filePath.endsWith("/")) {
                e = filePath + fileName;
            } else {
                e = filePath + "/" + fileName;
            }

            File f = new File(e);
            FileOutputStream out = new FileOutputStream(f);

            try {
                out.write(body, 0, body.length);
                out.flush();
            } finally {
                if(out != null) {
                    out.close();
                }

            }

        } catch (Exception var10) {
            throw new HttpCallerException(var10);
        }
    }

    static {
        int imaxConn = 20;
        if(maxConn != null) {
            try {
                imaxConn = Integer.parseInt(maxConn);
            } catch (Exception var9) {
                ;
            }
        }

        connMgr.setMaxTotal(imaxConn);
        connMgr.setDefaultMaxPerRoute(connMgr.getMaxTotal());
        RequestConfig.Builder configBuilder = RequestConfig.custom();
        int iconnTimeout = 2000;
        if(CONN_TIMEOUT != null) {
            try {
                iconnTimeout = Integer.parseInt(CONN_TIMEOUT);
            } catch (Exception var8) {
                ;
            }
        }

        configBuilder.setConnectTimeout(iconnTimeout);
        int isoTimeout = 30000;
        if(SO_TIMEOUT != null) {
            try {
                isoTimeout = Integer.parseInt(SO_TIMEOUT);
            } catch (Exception var7) {
                ;
            }
        }

        configBuilder.setSocketTimeout(isoTimeout);
        int icrTimeout = 2000;
        if(CR_TIMEOUT != null) {
            try {
                icrTimeout = Integer.parseInt(CR_TIMEOUT);
            } catch (Exception var6) {
                ;
            }
        }

        configBuilder.setConnectionRequestTimeout(icrTimeout);
        configBuilder.setStaleConnectionCheckEnabled(true);
        requestConfig = configBuilder.build();
    }

}
